package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.redis.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {


    /**
     * 测试用户注入
     * @param userInfo
     * @return
     */
    @RequestMapping("/info")
    @ResponseBody
    public Object info(UserInfo userInfo){
        return userInfo;
    }
    @RequestMapping("/user")
    @ResponseBody
    public Object user(@UserParam UserInfo userInfo){
        return userInfo;
    }

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private ITravelCommentService travelCommentService;
    //所有游记
    @RequestMapping("")
    public Object index(Model model,@ModelAttribute("qo") TravelQuery qo){
       model.addAttribute("pageInfo",travelService.query(qo));
        return "/travel/list";
    }
    @RequestMapping("detail")
    public Object index(Model model,Long id,@UserParam UserInfo userInfo){

        /**
         * 判断用户是否登录并且当前用户是否是自己
         *
         */


        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        detail.setTravelContent(content);
        model.addAttribute("detail",detail);
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);

        model.addAttribute("toasts",toasts);

        model.addAttribute("dest",dest);

        //sds
        model.addAttribute("sds",strategyDetailService.queryViewNumTop3(detail.getDest().getId()));
        //ts
        model.addAttribute("ts",travelService.queryViewNumTop3(detail.getDest().getId()));

        //查询所有评论
        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        model.addAttribute("list",page.getContent());
        return "/travel/detail";
    }

    //写游记页面
    @RequestMapping("input")
    public Object input(Model model,@UserParam UserInfo userInfo,Long id){
        if(userInfo==null){
           throw new LogicException("请先登录再写游记");
        }

        //回显
        if(id!=null){
            Travel travel = travelService.get(id);
            TravelContent content = travelService.getContent(id);
            travel.setTravelContent(content);
            model.addAttribute("tv",travel);

        }
        model.addAttribute("dests",destinationService.getDestsByDeep(3));
        return "/travel/input";
    }

    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Model model, Travel travel, HttpServletRequest request, HttpServletResponse response){

        //1用户
        String token = CookieUtil.getToken(request, response);
        UserInfo user = userInfoRedisService.getUserInfoByToken(token);
        if (user!=null){
            throw new LogicException("请先登录后再写游记");
        }

        //设置用户
        travel.setAuthor(user);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }


    @Value("${file.path}")
    private String basePath;
    //百度富文本框  图片 上传
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, basePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }



    //游记评论
    @RequestMapping("commentAdd")
    public Object commentAdd(Model model, TravelComment comment, @UserParam UserInfo userInfo){
        if (userInfo==null){
            throw new LogicException("请先登录");
        }
        comment.setCity(userInfo.getCity());
        comment.setHeadUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUsername(userInfo.getNickname());
        comment.setUserId(userInfo.getId());
        TravelComment travelComment = travelCommentService.saveOrUpdate(comment);
        //当前评论
        model.addAttribute("c",travelComment);
        //楼层
        model.addAttribute("floor",travelCommentService.getCount(comment.getTravelId()));
        return "/travel/commentTpl";
    }

    //游记评论
    @RequestMapping("commentDelete")
    @ResponseBody
    public Object commentDelete(String toid, @UserParam UserInfo userInfo){
        if (userInfo!=null){
            travelCommentService.commentDelete(toid);
        }
        return AjaxResult.SUCCESS;
    }
}
